"""
音频服务层
提供音频处理相关的业务逻辑
"""

import os
import logging
from typing import List, Dict, Any
from app.tools.audio_tools import AudioTools
from app.tools.utils import get_file_size_mb

class AudioService:
    """音频服务类"""
    
    def __init__(self, upload_folder: str, output_folder: str):
        """
        初始化音频服务
        
        Args:
            upload_folder: 上传文件夹路径
            output_folder: 输出文件夹路径
        """
        self.upload_folder = upload_folder
        self.output_folder = output_folder
        self.audio_tools = AudioTools()
        
    def extract_audio_service(self, video_file_path: str) -> Dict[str, Any]:
        """
        音频提取服务
        
        Args:
            video_file_path: 视频文件路径
            
        Returns:
            处理结果字典
        """
        try:
            # 获取原始文件信息
            original_size = get_file_size_mb(video_file_path)
            
            # 提取音频
            output_path = self.audio_tools.extract_audio(video_file_path, self.output_folder)
            
            # 获取输出文件信息
            output_size = get_file_size_mb(output_path)
            
            return {
                'success': True,
                'output_path': output_path,
                'original_size_mb': original_size,
                'output_size_mb': output_size,
                'message': '音频提取成功'
            }
        except Exception as e:
            logging.error(f"音频提取失败: {e}")
            return {
                'success': False,
                'error': str(e),
                'message': '音频提取失败'
            }
    
    def merge_audio_service(self, audio_paths: List[str]) -> Dict[str, Any]:
        """
        音频合并服务
        
        Args:
            audio_paths: 音频文件路径列表
            
        Returns:
            处理结果字典
        """
        try:
            # 计算总大小
            total_size = sum(get_file_size_mb(path) for path in audio_paths)
            
            # 合并音频
            output_path = self.audio_tools.merge_audio(audio_paths, self.output_folder)
            
            # 获取输出文件信息
            output_size = get_file_size_mb(output_path)
            
            return {
                'success': True,
                'output_path': output_path,
                'input_files_count': len(audio_paths),
                'total_input_size_mb': total_size,
                'output_size_mb': output_size,
                'message': '音频合并成功'
            }
        except Exception as e:
            logging.error(f"音频合并失败: {e}")
            return {
                'success': False,
                'error': str(e),
                'message': '音频合并失败'
            }
    
    def merge_audio_with_timestamps_service(self, audio_paths: List[str], timestamps: List[Dict[str, str]], gain_db=None, gains_db=None) -> Dict[str, Any]:
        """
        根据时间戳合并音频服务
        
        Args:
            audio_paths: 音频文件路径列表
            timestamps: 时间戳列表，每个元素为字典 {"start_time": "HH:MM:SS.mmm", "end_time": "HH:MM:SS.mmm"}
            
        Returns:
            处理结果字典
        """
        try:
            # 验证输入参数
            if not audio_paths:
                raise ValueError("音频文件列表不能为空")
            
            if not timestamps:
                raise ValueError("时间戳列表不能为空")
            
            if len(audio_paths) != len(timestamps):
                raise ValueError(f"音频文件数量({len(audio_paths)})与时间戳数量({len(timestamps)})不匹配")
            
            # 验证所有音频文件是否存在
            for audio_path in audio_paths:
                if not os.path.exists(audio_path):
                    raise FileNotFoundError(f"音频文件不存在: {audio_path}")
            
            # 计算总大小
            total_size = sum(get_file_size_mb(path) for path in audio_paths)
            
            # 根据时间戳合并音频
            output_path = self.audio_tools.merge_audio_with_timestamps(
                audio_paths,
                timestamps,
                self.output_folder,
                gain_db=gain_db,
                gains_db=gains_db,
            )
            
            # 获取输出文件信息
            output_size = get_file_size_mb(output_path)
            
            return {
                'success': True,
                'output_path': output_path,
                'input_files_count': len(audio_paths),
                'timestamps_count': len(timestamps),
                'total_input_size_mb': total_size,
                'output_size_mb': output_size,
                'message': '根据时间戳合并音频成功'
            }
        except Exception as e:
            logging.error(f"根据时间戳合并音频失败: {e}")
            return {
                'success': False,
                'error': str(e),
                'message': '根据时间戳合并音频失败'
            } 